﻿using Abp.Application.Services;
using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Abp.Extensions;
using iTextSharp.text;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using MySqlX.XDevAPI.Common;
using SportsPlatform.Base;
using SportsPlatform.Consts;
using SportsPlatform.Dto.PermissionManagement.CompanyInfo;
using SportsPlatform.Dto.SportBusiness.Category;
using SportsPlatform.Dto.SportBusiness.CompetitionAchievementInfo;
using SportsPlatform.Dto.SportBusiness.GetPaymentOrderInfo;
using SportsPlatform.Dto.SportBusiness.PaymentOrderOperationInfo;
using SportsPlatform.Dto.SportBusiness.RegistrationInfo;
using SportsPlatform.Enums;
using SportsPlatform.Global;
using SportsPlatform.Helpers;
using SportsPlatform.Model.PermissionManagement;
using SportsPlatform.Model.SportBusiness;
using SportsPlatform.Query.Competition;
using SportsPlatform.Query.SportBusiness.Category;
using SportsPlatform.Query.SportBusiness.GetPaymentOrderInfo;
using SportsPlatform.Query.SportBusiness.PaymentOrderInfo;
using SportsPlatform.SportBusiness.ISportBusiness;
using SportsPlatform.SqlExecuter;
using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using static iTextSharp.text.pdf.AcroFields;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace SportsPlatform.SportBusiness.SportBusiness
{
    /// <summary>
    /// 
    /// </summary>
    [RemoteService(false)]  //隐藏自动生成的WebApi
    public class PaymentOrderInfoService : SportsPlatformAppServiceBase, IPaymentOrderInfoService
    {
        /// <summary>
        /// 
        /// </summary>
        private readonly IRepository<PaymentOrderInfo, Guid> _repository;

        /// <summary>
        /// 用户仓储
        /// </summary>
        private readonly IRepository<Employee, Guid> _employeeRepository;

        /// <summary>
        /// 平台端用户仓储
        /// </summary>
        private readonly IRepository<UserInfo, Guid> _userInfoRepository;

        /// <summary>
        /// 赛事仓储
        /// </summary>
        private readonly IRepository<Competition, Guid> _competitionRepository;

        /// <summary>
        /// 创建赛事商户仓储
        /// </summary>
        private readonly IRepository<CompanyInfo, Guid> _companyInfoRepository;

        /// <summary>
        /// 比赛项目仓储
        /// </summary>
        private readonly IRepository<CompetitionProject, Guid> _competitionProjectrepository;

        /// <summary>
        /// 报名信息仓储
        /// </summary>
        private readonly IRepository<RegistrationInfo, Guid> _registrationInfoRepository;

        /// <summary>
        /// 团队用户仓储
        /// </summary>
        private readonly IRepository<TeamUser, Guid> _teamUserRopository;

        /// <summary>
        /// 团队仓储
        /// </summary>
        private readonly IRepository<Team, Guid> _teamRopository;

        private readonly IRepository<PaymentOrderOperationInfo, Guid> _paymentOrderOperationInfoRepository;
        IWebHostEnvironment _web;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="repository"></param>
        /// <param name="sqlExecuterRepository"></param>
        public PaymentOrderInfoService(IRepository<PaymentOrderInfo, Guid> repository
            , IRepository<Employee, Guid> employeeRepository, IRepository<Competition, Guid> competitionRepository
            , IRepository<CompanyInfo, Guid> companyInfoRepository, IRepository<CompetitionProject, Guid> competitionProjectrepository
            , IRepository<RegistrationInfo, Guid> registrationInfoRepository, IRepository<Team, Guid> teamRopository,
            IRepository<TeamUser, Guid> teamUserRopository, IRepository<PaymentOrderOperationInfo, Guid> paymentOrderOperationInfoRepository,
            IRepository<UserInfo, Guid> userInfoRepository, IWebHostEnvironment web, IHttpContextAccessor context) : base(context)
        {
            _repository = repository;
            _employeeRepository = employeeRepository;
            _competitionRepository = competitionRepository;
            _companyInfoRepository = companyInfoRepository;
            _competitionProjectrepository = competitionProjectrepository;
            _registrationInfoRepository = registrationInfoRepository;
            _teamRopository = teamRopository;
            _teamUserRopository = teamUserRopository;
            _paymentOrderOperationInfoRepository = paymentOrderOperationInfoRepository;
            _userInfoRepository = userInfoRepository;
            _web = web;

        }

        /// <summary>
        /// 添加订单信息
        /// </summary>
        /// <param name="infoQuery">传入参数</param>
        /// <returns></returns>
        public async Task<ResultByIdDto> AddInfo(AddPaymentOrderInfoQuery infoQuery)
        {
            ResultByIdDto resultDto = new ResultByIdDto();
            try
            {
                var order = ObjectMapper.Map<PaymentOrderInfo>(infoQuery);

                var user = await _employeeRepository.GetAsync(infoQuery.EmployeeID);
                if (user.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "当前用户不存在";
                    return resultDto;
                }
                //赛事信息
                var competition = await _competitionRepository.GetAsync(infoQuery.CompetitionID);
                if (competition.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "当前赛事不存在";
                    return resultDto;
                }
                //赛事商户信息
                var company = await _companyInfoRepository.GetAsync(infoQuery.CompanyID);
                if (company.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "当前赛事商户不存在";
                    return resultDto;
                }
                order.SubmitTime = DateTime.Now;
                order.CreateTime = DateTime.Now;
                order.CreateUserId = user.Id;

                var info = await _repository.InsertAndGetIdAsync(order);

                resultDto.Code = !info.IsNullAndEmpty() ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = !info.IsNullAndEmpty();
                resultDto.Message = !info.IsNullAndEmpty() ? "添加成功" : "添加失败";
                resultDto.Data = !info.IsNullAndEmpty() ? new Base.Dto() { Id = info } : null;
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 更新订单信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> UpdatePaymentOrderInfo(UpdatePaymentOrderInfoQuery query)
        {
            BaseResultDto dto = new BaseResultDto();
            try
            {
                var payorderinfo = await _repository.FirstOrDefaultAsync(query.Id);
                if (payorderinfo != null)
                {
                    if (string.IsNullOrEmpty(Enum.GetName(typeof(PaymentStatusEnum), query.PaymentStatus)))
                    {
                        dto.IsSuccess = false;
                        dto.Code = HttpResultCode.Fail;
                        dto.Message = "传入支付状态不合法！";
                        return dto;
                    }
                    if (string.IsNullOrEmpty(Enum.GetName(typeof(OrderStatusEnum), query.OrderStatus)))
                    {
                        dto.IsSuccess = false;
                        dto.Code = HttpResultCode.Fail;
                        dto.Message = "传入订单状态不合法！";
                        return dto;
                    }
                    payorderinfo.PaymentStatus = query.PaymentStatus;
                    payorderinfo.PaymentTime = query.PaymentTime;
                    payorderinfo.OrderStatus = query.OrderStatus;
                    payorderinfo.OrderOddNumbers = query.OrderOddNumbers;
                    payorderinfo.OrderNumber = query.OrderNumber;
                    payorderinfo.UpdateTime = DateTime.Now;
                    payorderinfo.UpdateUserId = payorderinfo.EmployeeID;
                    await _repository.UpdateAsync(payorderinfo);
                    dto.IsSuccess = true;
                    dto.Code = HttpResultCode.Success;
                    dto.Message = "修改成功！";
                }
                else
                {
                    dto.IsSuccess = false;
                    dto.Code = HttpResultCode.Error;
                    dto.Message = "未查询到传入Id信息！";
                }
            }
            catch (Exception ex)
            {
                dto.IsSuccess = false;
                dto.Code = HttpResultCode.Error;
                dto.Message = ex.Message.ToString();
            }
            return dto;
        }

        /// <summary>
        /// 获取赛事列表
        /// </summary>
        /// <returns></returns>
        public async Task<ResultListDto<GetCompetitionSelectItemQuery>> GetAll()
        {
            var resultDto = new ResultListDto<GetCompetitionSelectItemQuery>();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                var res = (await _competitionRepository.GetAllListAsync())
                    .WhereIF(token.CompanyId != null, info => info.Merchants == token.CompanyId)
                    .ToList();

                resultDto.Count = res.Count;
                resultDto.Code = res.Count > 0 ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = res.Count > 0 ? true : false;
                resultDto.Message = res.Count > 0 ? "查询成功" : "未查询到数据";
                resultDto.Data = res.Count > 0 ? ObjectMapper.Map<List<GetCompetitionSelectItemQuery>>(res) : null;
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 获取赛事商户列表
        /// </summary>
        /// <returns></returns>
        public async Task<ResultListDto<GetCompanysSelectItemListQuery>> GetCompanysList()
        {
            var resultDto = new ResultListDto<GetCompanysSelectItemListQuery>();
            try
            {
                var res = await _companyInfoRepository.GetAllListAsync();

                resultDto.Count = res.Count;
                resultDto.Code = res.Count >= 0 ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = res.Count >= 0 ? true : false;
                resultDto.Message = res.Count > 0 ? "查询成功" : "未查询到数据";
                resultDto.Data = res.Count > 0 ? ObjectMapper.Map<List<GetCompanysSelectItemListQuery>>(res) : null;
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 获取订单信息特定属性接口
        /// </summary>
        /// <returns></returns>
        public async Task<ResultDto<GetPaymentOderInfoDto>> GetByPaymentOrderInfoDetailsId(GetInfoQuery query)
        {
            ResultDto<GetPaymentOderInfoDto> result = new ResultDto<GetPaymentOderInfoDto>();
            try
            {
                var res = await _repository.GetAsync(query.Id);


                result.Code = !res.IsNullAndEmpty() ? HttpResultCode.Success : HttpResultCode.SqlError;
                result.IsSuccess = !res.IsNullAndEmpty() ? true : false;
                result.Message = !res.IsNullAndEmpty() ? "查询成功" : "未查询到数据";
                result.Data = !res.IsNullAndEmpty() ? new GetPaymentOderInfoDto
                {
                    OrderOddNumbers = res.OrderOddNumbers,
                    OrderSource = Enum.GetName(typeof(SourceEnum), res.OrderSource),
                    PaymentFee = res.PaymentFee,
                    PaymentMethod = Enum.GetName(typeof(PaymentMethodEnum), res.PaymentMethod),
                    PaymentTime = res.PaymentTime != null ? ((DateTime)res.PaymentTime).ToString("yyyy-MM-dd") : null,
                    SubmitTime = res.SubmitTime.ToString("yyyy-MM-dd")
                } : null;
            }
            catch (Exception ex)
            {
                result.Code = HttpResultCode.Error;
                result.IsSuccess = false;
                result.Data = null;
                result.Message = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 列表查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public async Task<PagePagingDto<PaymentOrderInfoListDto>> GetPaymentOrderInfoList(GetPaymentOrderInfoQuery query)
        {
            PagePagingDto<PaymentOrderInfoListDto> result = new PagePagingDto<PaymentOrderInfoListDto>();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                List<PaymentOrderInfoListDto> infos = new List<PaymentOrderInfoListDto>();
                var asyncres = (await _repository.GetAllListAsync())
                    .WhereIF(token.CompanyId != null, info => info.CompanyID == token.CompanyId).ToList();
                string competitonName = "";
                string companyName = "";
                var employees = await _employeeRepository.GetAllListAsync(e => e.IsDeleted == false);
                var competitions = await _competitionRepository.GetAllListAsync(c => c.IsDeleted == false);
                var companys = await _companyInfoRepository.GetAllListAsync(c => c.IsDeleted == false);
                if (asyncres.Count > 0)
                {
                    asyncres.ForEach(item =>
                    {
                        //用户信息
                        var employee = employees.FirstOrDefault(e => e.Id == item.EmployeeID);
                        //赛事信息
                        var competition = competitions.FirstOrDefault(c => c.Id == item.CompetitionID);

                        //赛事商户信息
                        var company = companys.FirstOrDefault(c => c.Id == item.CompanyID);

                        var phone = "";
                        if (!string.IsNullOrWhiteSpace(item.ContactTel))
                        {
                            if (item.ContactTel.Length == 11)
                            {
                                phone = item.ContactTel.Substring(0, 3) + "****" + item.ContactTel.Substring(item.ContactTel.Length - 4, 4);
                            }
                            else
                            {
                                phone = "";
                            }
                        }

                        infos.Add(new PaymentOrderInfoListDto
                        {
                            ContactTel = phone,
                            Id = item.Id,
                            PaymentFee = "￥" + item.PaymentFee.ToString(),
                            PaymentMethod = Enum.GetName(typeof(PaymentMethodEnum), item.PaymentMethod),
                            PaymentStatus = Enum.GetName(typeof(PaymentStatusEnum), item.PaymentStatus),
                            PaymentTime = !item.PaymentTime.IsNullAndEmpty() ? ((DateTime)item.PaymentTime).ToString("yyyy-MM-dd") : "未支付",
                            SubmitTime = item.SubmitTime.ToString("yyyy-MM-dd"),
                            CompanyName = !company.IsNullAndEmpty() ? company.CompanyName : "",
                            CompetitionName = !competition.IsNullAndEmpty() ? competition.Name : "",
                            EmployeeName = !employee.IsNullAndEmpty() ? employee.RealName : ""
                        }); ;
                    });


                    if (!query.CompetitionID.IsNullAndEmpty())
                    {
                        Guid guid = Guid.Parse(query.CompetitionID);
                        var competition = await _competitionRepository.GetAsync(guid);
                        competitonName = competition.Name;
                    }

                    if (!query.CompanyID.IsNullAndEmpty())
                    {
                        Guid guid = new Guid(query.CompanyID);
                        var company = await _companyInfoRepository.GetAsync(guid);
                        companyName = company.CompanyName;
                    }


                    var res = infos.WhereIF(!query.key.IsNullAndEmpty(), c => c.EmployeeName.Contains(query.key) || c.ContactTel.Contains(query.key))
                          .WhereIF(!companyName.IsNullAndEmpty(), c => c.CompanyName.Contains(companyName))
                          .WhereIF(!query.PaymentStatus.IsNullAndEmpty(), c => c.PaymentStatus == Enum.GetName(typeof(PaymentStatusEnum), query.PaymentStatus))
                          .WhereIF(!competitonName.IsNullAndEmpty(), c => c.CompetitionName.Contains(competitonName)).OrderByDescending(c => Convert.ToDateTime(c.SubmitTime)).ToList();


                    var page = res.ToPage(query.PageIndex, query.PageSize).ToList();


                    result.TotalCount = res.Count;
                    result.Code = page.Count >= 0 ? HttpResultCode.Success : HttpResultCode.SqlError;
                    result.IsSuccess = page.Count >= 0 ? true : false;
                    result.Message = page.Count > 0 ? "查询成功" : "未查询到数据";
                    result.Data = page.Count > 0 ? page : null;
                }

            }
            catch (Exception ex)
            {
                result.TotalCount = 0;
                result.Code = HttpResultCode.Error;
                result.IsSuccess = false;
                result.Data = null;
                result.Message = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 获取订单信息标题属性接口
        /// </summary>
        /// <param name="query">传入参数</param>
        /// <returns></returns>
        public async Task<ResultDto<GetPaymentOderInfoTitleDto>> GetPaymentOderInfoTitleById(GetInfoQuery query)
        {
            ResultDto<GetPaymentOderInfoTitleDto> result = new ResultDto<GetPaymentOderInfoTitleDto>();
            try
            {
                var res = await _repository.GetAsync(query.Id);

                var company = await _companyInfoRepository.GetAsync(res.CompanyID);

                result.Code = !res.IsNullAndEmpty() ? HttpResultCode.Success : HttpResultCode.SqlError;
                result.IsSuccess = !res.IsNullAndEmpty() ? true : false;
                result.Message = !res.IsNullAndEmpty() ? "查询成功" : "未查询到数据";
                result.Data = !res.IsNullAndEmpty() ? new GetPaymentOderInfoTitleDto
                {
                    CompanyID = res.CompanyID,
                    OrderSource = Enum.GetName(typeof(SourceEnum), res.OrderSource),
                    PaymentFee = res.PaymentFee,
                    PaymentMethod = Enum.GetName(typeof(PaymentMethodEnum), res.PaymentMethod),
                    PaymentTime = res.PaymentTime != null ? ((DateTime)res.PaymentTime).ToString("yyyy-MM-dd HH:mm:ss") : null,
                    SubmitTime = res.SubmitTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    CompanyName = company.CompanyName,
                    OrderNumber = res.OrderNumber,
                    OrderStatus = Enum.GetName(typeof(OrderStatusEnum), res.OrderStatus)
                } : null;
            }
            catch (Exception ex)
            {
                result.Code = HttpResultCode.Error;
                result.IsSuccess = false;
                result.Data = null;
                result.Message = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 添加订单详情备注
        /// </summary>
        /// <param name="query">传入参数</param>
        /// <returns></returns>
        public async Task<BaseResultDto> AddOrderNotes(AddOrderNotesQuery query)
        {
            BaseResultDto resultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                var res = await _repository.GetAsync(query.Id);
                var user = await _userInfoRepository.GetAsync(token.Id);
                if (user.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Error;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "当前用户不存在";
                    return resultDto;
                }
                if (res.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Error;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "当前标识不存在";
                    return resultDto;
                }
                var operation = new PaymentOrderOperationInfo
                {
                    IsDeleted = false,
                    CreateTime = DateTime.Now,
                    OperationName = user.UserName,
                    OperationTime = DateTime.Now,
                    PaymentOrderID = query.Id,
                    OrderState = res.OrderSource,
                    PaymentState = res.PaymentStatus
                };
                if (!query.OrderNotes.IsNullAndEmpty())
                {
                    res.OrderNotes = query.OrderNotes;
                    operation.OperationDetails = $"备注订单(备注内容:{query.OrderNotes})";
                }

                if (!query.OrderCloseNotes.IsNullAndEmpty())
                {
                    res.OrderCloseNotes = query.OrderCloseNotes;
                    operation.OperationDetails = $"关闭订单(关闭原因:{query.OrderCloseNotes})";

                }

                await _paymentOrderOperationInfoRepository.InsertAsync(operation);

                var info = await _repository.UpdateAsync(res);

                resultDto.Code = !info.IsNullAndEmpty() ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = !info.IsNullAndEmpty();
                resultDto.Message = !info.IsNullAndEmpty() ? "添加成功" : "添加失败";
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 获取费用信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<GetPriceInfoQuery>> GetPriceInfo(GetInfoQuery query)
        {
            var resultDto = new ResultDto<GetPriceInfoQuery>();
            try
            {
                var orderInfo = await _repository.GetAsync(query.Id);

                var competition = await _competitionRepository.GetAsync(orderInfo.CompetitionID);

                var competitionProject = await _competitionProjectrepository.FirstOrDefaultAsync(c => c.CompetitionId == competition.Id);

                var price = new GetPriceInfoQuery
                {
                    CompeteProjectName = competitionProject.Name,
                    Money = competition.Money,
                    TeamMaxUserNum = competitionProject.TeamMaxUserNum,
                    Sum = competition.Money * competitionProject.TeamMaxUserNum
                };


                resultDto.Code = HttpResultCode.Success;
                resultDto.IsSuccess = true;
                resultDto.Message = "查询成功";
                resultDto.Data = price;
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 获取提交用户信息
        /// </summary>
        /// <returns></returns>
        public async Task<ResultDto<GetCommitEmployeeQuery>> GetCommitEmployee(GetInfoQuery query)
        {
            var resultDto = new ResultDto<GetCommitEmployeeQuery>();
            try
            {
                var orderInfo = await _repository.GetAsync(query.Id);

                var commitEmployee = await _employeeRepository.GetAsync(orderInfo.EmployeeID);


                resultDto.Code = HttpResultCode.Success;
                resultDto.IsSuccess = true;
                resultDto.Message = "查询成功";
                resultDto.Data = new GetCommitEmployeeQuery
                {
                    Name = commitEmployee.RealName,
                    Phone = commitEmployee.Phone.Substring(0, 3) + "****" + commitEmployee.Phone.Substring(commitEmployee.Phone.Length - 4, 4)
                };
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 获取报名信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultListDto<GetRegistrationInfoQuery>> GetRegistrationInfo(GetInfoQuery query)
        {
            var resultDto = new ResultListDto<GetRegistrationInfoQuery>();
            try
            {
                var list = new List<GetRegistrationInfoQuery>();
                var paymentOrderInfo = await _repository.GetAsync(query.Id);
                if (paymentOrderInfo.IsNullAndEmpty())
                {
                    return new ResultListDto<GetRegistrationInfoQuery>()
                    {
                        IsSuccess = false,
                        Code = HttpResultCode.NotData,
                        Message = "未查询到数据"
                    };
                }


                var registrationInfos = await _registrationInfoRepository.GetAllListAsync(r => r.PaymentOrderId == paymentOrderInfo.Id && r.IsDeleted == false);
                var employees = await _employeeRepository.GetAllListAsync(e => e.IsDeleted == false);
                var competitionProjects = await _competitionProjectrepository.GetAllListAsync(c => c.IsDeleted == false);
                var competitions = await _competitionRepository.GetAllListAsync(c => c.IsDeleted == false && c.IsEnable == 1);
                var teamUseritems = await _teamUserRopository.GetAllListAsync(t => t.IsDeleted == false);
                var teamItems = await _teamRopository.GetAllListAsync(t => t.IsDeleted == false);
                foreach (var item in registrationInfos)
                {
                    var employee = employees.FirstOrDefault(e => e.Id == item.EmployeeId);
                    var competitionProject = competitionProjects.FirstOrDefault(c => c.Id == item.CompetitionProjectId);
                    var competition = competitions.FirstOrDefault(c => c.Id == item.CompetitionId);
                    var teamUseritem = teamUseritems.FirstOrDefault(t => t.EmployeeId == item.EmployeeId);
                    var teamItem = teamItems.FirstOrDefault(t => t.Id == teamUseritem.TeamId);
                    list.Add(new GetRegistrationInfoQuery
                    {
                        CompeteName = employee.RealName,
                        Address = competitionProject.DetailsAddress,
                        CompeteIdNo = item.CompeteIdNo,
                        CompeteTeamName = item.CompeteTeamName,
                        CompeteTel = item.CompeteTel,
                        CompetitionName = competition.Name,
                        CompetitionProjectName = competitionProject.Name,
                        GameBeginTime = competitionProject.GameBeginTime.ToString("yyyy-MM-dd"),
                        RegistrationStatus = Enum.GetName(typeof(RegistrationStatusEnum), item.RegistrationStatus),
                        SensorNumber = item.SensorNumber,
                        TeamName = teamItem.TeamName,
                    });
                }


                resultDto.Count = registrationInfos.Count;
                resultDto.Code = registrationInfos.Count > 0 ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = registrationInfos.Count > 0 ? true : false;
                resultDto.Message = registrationInfos.Count > 0 ? "查询成功" : "未查询到数据";
                resultDto.Data = registrationInfos.Count > 0 ? list : null;
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 获取操作记录列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<DownloadEventsSessionCompetitionAchievementDto>> ExportActionInfo(GetActionInfoQuery query)
        {
            try
            {
                var res = await _paymentOrderOperationInfoRepository.GetAllListAsync(p => p.PaymentOrderID == query.Id);

                if (res.Count > 0)
                {
                    var ordeActions = res.WhereIF(!query.StartTime.IsNullOrEmpty() &&
                        !query.EndTime.IsNullOrEmpty(), p => p.CreateTime >= Convert.ToDateTime(query.StartTime) &&
                    p.CreateTime <= Convert.ToDateTime(query.EndTime)).OrderByDescending(o => o.CreateTime).ToList();
                    if (ordeActions.Count > 0)
                    {
                        DataTable dataTable = new DataTable();
                        dataTable.Columns.Add("操作用户");
                        dataTable.Columns.Add("操作时间");
                        dataTable.Columns.Add("操作详情");
                        dataTable.Columns.Add("订单状态");
                        dataTable.Columns.Add("付款状态");
                        ordeActions.ToList().ForEach(info =>
                        {
                            DataRow row = dataTable.NewRow();
                            row["操作用户"] = info.OperationName;
                            row["操作时间"] = info.OperationTime.ToString("yyy-MM-dd  HH:mm");
                            row["操作详情"] = info.OperationDetails;
                            row["订单状态"] = Enum.GetName(typeof(RegistrationStatusEnum), info.OrderState);
                            row["付款状态"] = Enum.GetName(typeof(PaymentStatusEnum), info.PaymentState);
                            dataTable.Rows.Add(row);
                        });
                        return new ResultDto<DownloadEventsSessionCompetitionAchievementDto>()
                        {
                            Data = new DownloadEventsSessionCompetitionAchievementDto() { Url = ExportHelper.DataTableToExcel(_web, dataTable, $"操作记录") },
                            IsSuccess = true,
                            Code = (int)HttpResultCode.Success,
                            Message = "成功"
                        };
                    }
                    else
                    {
                        return new ResultDto<DownloadEventsSessionCompetitionAchievementDto>()
                        {
                            IsSuccess = false,
                            Code = HttpResultCode.NotData,
                            Message = $"该时间段{query.StartTime}至{query.EndTime},未查询到数据"
                        };
                    }
                }
                else
                {
                    return new ResultDto<DownloadEventsSessionCompetitionAchievementDto>()
                    {
                        IsSuccess = false,
                        Code = HttpResultCode.NotData,
                        Message = "未查询到数据"
                    };
                }

            }
            catch (Exception ex)
            {
                return new ResultDto<DownloadEventsSessionCompetitionAchievementDto>()
                {
                    IsSuccess = false,
                    Code = (int)HttpResultCode.Error,
                    Message = ex.Message
                };
            }
        }

        /// <summary>
        /// 获取操作记录列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultListDto<PaymentOrderOperationInfoListDto>> GetOrderInfoList(GetInfoQuery query)
        {
            var resultDto = new ResultListDto<PaymentOrderOperationInfoListDto>();
            try
            {


                var paymentOrders = await _paymentOrderOperationInfoRepository.GetAllListAsync(p => p.PaymentOrderID == query.Id);
                if (paymentOrders.Count > 0)
                {

                    var res = paymentOrders.WhereIF(!query.StartTime.IsNullOrEmpty() && !query.EndTime.IsNullOrEmpty(), p => p.CreateTime >= Convert.ToDateTime(query.StartTime) && p.CreateTime <= Convert.ToDateTime(query.EndTime)).OrderByDescending(p => p.CreateTime)
                        .Select(p => new PaymentOrderOperationInfoListDto
                        {
                            OperationDetails = p.OperationDetails,
                            OperationName = p.OperationName,
                            OperationTime = p.OperationTime.ToString("yyyy-MM-dd HH:mm"),
                            OrderState = Enum.GetName(typeof(RegistrationStatusEnum), p.OrderState),
                            PaymentState = Enum.GetName(typeof(RegistrationStatusEnum), p.PaymentState)
                        }).ToList();

                    resultDto.Data = res;
                }


                resultDto.Count = paymentOrders.Count;
                resultDto.Code = paymentOrders.Count >= 0 ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = paymentOrders.Count >= 0 ? true : false;
                resultDto.Message = paymentOrders.Count > 0 ? "查询成功" : "未查询到数据";
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }
    }
}
